package com.yxw.yxnet_cd_center.customer_service.utils;

import com.yxw.yxnet_cd_center.common.dto.HuaWeiSmsDTO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.common.utils.IdWorkerUtils;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import com.yxw.yxnet_cd_center.common.utils.BaseResult;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import org.apache.http.ParseException;
/**
 * @author Administrator
 */
@ConfigurationProperties(prefix = "spring.cloud.hwy.sms")
@Data
@Component
@Slf4j
public class HuaWeiSmsUtil {
    /**
     * 无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
     */
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    /**
     * 无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
     */
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";
    /**
     * 必填,请参考"开发准备"获取如下数据,替换为实际值
     * APP接入地址+接口访问URI
     */
    private String url;
    /**
     * 应用管理中的 APP_Key
     */
    private String appKey;
    /**
     * 应用管理中的APP_Secret
     */
    private String appSecret;
    /**
     * 签名管理中的国内短信签名通道号或国际/港澳台短信通道号
     */
    private String sender;
    /**
     * 模板管理中的模板ID
     */
    private String templateId;
    /**
     * 条件必填,国内短信关注,当templateId指定的模板类型为通用模板时生效且必填,必须是已审核通过的,与模板类型一致的签名名称
     * 国际/港澳台短信不用关注该参数
     * 签名名称
     */
    private String signature;

    /**
     * 发送短信
     * @param dto 手机号
     */
    public String sendSmsCode(HuaWeiSmsDTO dto){
        String statusCallBack = "";
        String body = buildRequestBody(dto.getSender(), dto.getPhone(), dto.getTemplateId(), dto.getTemplateParas(), statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            throw new BaseException("请求体body为空");
        }
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            throw new BaseException("wsse header is null.");
        }

        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }

        HttpResponse response = null;
        try {
            assert client != null;
            response = client.execute(RequestBuilder.create("POST")
                    .setUri(url + "/sms/batchSendSms/v1")
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BaseException("发送异常"+e.getMessage());
        }
        String bodyStr ="";
        try{
            bodyStr =EntityUtils.toString(response.getEntity());
            log.info("响应请求==================================="+bodyStr);
        }catch (Exception e){
            log.error(e.getMessage());
            throw new BaseException(e.getMessage());
        }
        return bodyStr;
    }
    /**
     * 发送短信
     * @param dto 手机号
     */
    public BaseResult sendSms(HuaWeiSmsDTO dto){
        String statusCallBack = "";
        String body = buildRequestBody(dto.getSender(), dto.getPhone(), dto.getTemplateId(), dto.getTemplateParas(), statusCallBack, signature);
        if (null == body || body.isEmpty()) {
            //throw new BaseException("请求体body为空");
            return BaseResult.failed("请求体body为空");
        }
        String wsseHeader = buildWsseHeader(appKey, appSecret);
        if (null == wsseHeader || wsseHeader.isEmpty()) {
            //throw new BaseException("wsse header is null.");
            BaseResult.failed("wsse header is null.");
        }

        CloseableHttpClient client = null;
        try {
            client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            //log.error(e.getMessage());
            //throw new BaseException(e.getMessage());
            return BaseResult.failed(e.getMessage());
        }

        HttpResponse response = null;
        try {
            assert client != null;
            response = client.execute(RequestBuilder.create("POST")
                    .setUri(url + "/sms/batchSendSms/v1")
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());
        } catch (IOException e) {
            //log.error(e.getMessage());
            //throw new BaseException("发送异常"+e.getMessage());
            return BaseResult.failed(e.getMessage());
        }
        String bodyStr ="";
        try{
            bodyStr =EntityUtils.toString(response.getEntity());
            //log.info("响应请求==================================="+bodyStr);
        }catch (IOException | ParseException e){
            //log.error(e.getMessage());
            //throw new BaseException(e.getMessage());
            return BaseResult.failed(e.getMessage());
        }
        return BaseResult.success(bodyStr);
        //return bodyStr;
    }
    /**
     * 构造请求Body体
     * @param sender 签名管理中的国内短信签名通道号或国际/港澳台短信通道号
     * @param receiver 接收手机号
     * @param templateId 模板管理中的模板ID
     * @param templateParas 验证码
     * @param statusCallbackUrl 状态回调地址
     * @param signature         | 签名名称,使用国内短信通用模板时填写
     * @return String
     */
    static String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                   String statusCallbackUrl, String signature) {
        if (null == sender || null == receiver || null == templateId || sender.isEmpty() || receiver.isEmpty()
                || templateId.isEmpty()) {
            throw new BaseException("buildRequestBody(): sender, receiver or templateId is null.");
        }
        List<NameValuePair> keyValues = new ArrayList<>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));
        if (null != templateParas && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }
        if (null != statusCallbackUrl && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }
        if (null != signature && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, StandardCharsets.UTF_8);
    }

    /**
     * 构造X-WSSE参数值
     * @param appKey 应用管理中的 appKey
     * @param appSecret 应用管理中的 appSecret
     * @return String
     */
    static String buildWsseHeader(String appKey, String appSecret) {
        if (null == appKey || null == appSecret || appKey.isEmpty() || appSecret.isEmpty()) {
            throw new BaseException("buildWsseHeader(): appKey or appSecret is null.");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date());
        String nonce = IdWorkerUtils.getInstance().nextId() + "";

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);
        String passwordDigestBase64Str = Base64.getEncoder().encodeToString(hexDigest.getBytes());

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }
}
